from contextlib import asynccontextmanager
import importlib

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from core.models import create_db_and_tables
from application import urls, settings

from fastapi.openapi.docs import get_swagger_ui_html
from fastapi import applications

def swagger_monkey_patch(*args, **kwargs):
    return get_swagger_ui_html(
        *args, **kwargs,
        swagger_js_url='/static/ui/swagger-ui/swagger-ui-bundle.min.js',
        swagger_css_url='/static/ui/swagger-ui/swagger-ui.min.css'
    )
applications.get_swagger_ui_html = swagger_monkey_patch

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Not needed if you setup a migration system like Alembic
    await create_db_and_tables()
    yield

def import_modules(modules: list, desc: str, **kwargs):
    for module in modules:
        module_pag = importlib.import_module(module[0:module.rindex(".")])
        getattr(module_pag, module[module.rindex(".") + 1:])(**kwargs)

app = FastAPI(lifespan=lifespan)

app.mount("/static", StaticFiles(directory="static"))

# 引入应用中的路由
for url in urls.urlpatterns:
    app.include_router(url["ApiRouter"], prefix=url["prefix"], tags=url["tags"])

# 将中间件添加到主程序中
import_modules(settings.MIDDLEWARES, "中间件", app=app)

# auth demo
# @app.get("/authenticated-route")
# async def authenticated_route(user: User = Depends(current_active_user)):
#     return {"message": f"Hello {user.email}!"}
